package com.jxlgzwh.elasticsearch;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: yezhou
 * @Date: 2019/5/24 20:13
 * @Version 1.0
 */

@Slf4j
@RestController
public class ElasticSearchController {

    @Resource
    private RestHighLevelClient client;

    @GetMapping("/search")
    @ResponseBody
    public String search() throws IOException {
//        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.165.239", 9200, "http")));

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        boolQueryBuilder.must(QueryBuilders.termQuery("loglvl.keyword", "ERROR"));
//        boolQueryBuilder.must(QueryBuilders.wildcardQuery("loglvl.keyword", "INFO"));
//        boolQueryBuilder.must(QueryBuilders.rangeQuery("field").gt("value"));
//        boolQueryBuilder.must(QueryBuilders.termsQuery("loglvl.keyword", "INFO"));

//        boolQueryBuilder.must(QueryBuilders.matchQuery("loglvl", "ERROR"));

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort("@timestamp", SortOrder.DESC);
        sourceBuilder.from(0);
        sourceBuilder.size(10);

        RequestOptions requestOptions = RequestOptions.DEFAULT;

        SearchRequest searchRequest = new SearchRequest("thaipay");
        //searchRequest.searchType(SearchType.QUERY_THEN_FETCH);
        searchRequest.source(sourceBuilder);
        log.info(searchRequest.toString());
        SearchResponse searchResponse = client.search(searchRequest, requestOptions);
        return JSON.toJSONString(searchResponse);
    }

}